//
//  WEXComposeViewController.swift
//  microBlog
//
//  Created by apple on 16/4/25.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit
import SVProgressHUD

class WEXComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        setupUI()
        
    }
    
    private func setupUI(){
        
        setupNav()
        view.backgroundColor = UIColor.whiteColor()
//        文字
        view.addSubview(tv_textView)
        
//        图片界面
        tv_textView.addSubview(cv_pictureView) 
//        view.addSubview(cv_pictureView)
//        工具栏
        view.addSubview(stk_toolBar)

        
//        文字界面的约束
        tv_textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.view)
        }
        
//        工具栏的约束
        stk_toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
//        图片视图的约束
        cv_pictureView.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(self.view).offset(10)
            make.width.equalTo(tv_textView).offset(-20)
            make.top.equalTo(self.view).offset(150)
            make.height.equalTo(cv_pictureView.snp_width)
        }
        
        
//        键盘位移的监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
//        键盘表情按钮的点击的监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonClick:", name: WEXEmoticonButtonClickNotification, object: nil)
        
//        删除按钮的监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteButtonClick", name: WEXEmoticonDeleteButtonNotification, object: nil)
    }
    
    
    

    // 设置导航栏视图
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
        
        navigationItem.titleView = lb_title
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btn_rightButton)
        
        navigationItem.rightBarButtonItem?.enabled = false
        
    }
    
    
    // 选择图片
    private func selectPicture() {
        
        let vc = UIImagePickerController()
        
        vc.delegate = self
        
        presentViewController(vc, animated: true, completion: nil)
        
        
        
    }
    
    // 选择键盘
    private func selectKeyBoard(){
        
        tv_textView.inputView = tv_textView.inputView == nil ? uv_keyBoard : nil
        
//        控制器告诉toolBar现在是什么键盘
        stk_toolBar.isSystemKeyBoard = tv_textView.inputView == nil
        
        tv_textView.reloadInputViews()
        
        if !tv_textView.isFirstResponder(){
            
            tv_textView.becomeFirstResponder()
        }
        
    }
    
    
    // MARK: - 响应方法
    // 表情按钮的点击
    @objc private func emoticonButtonClick(noti: NSNotification){
        
//        获取传输过来的表情模型
        let emoticon = noti.userInfo!["emoticon"] as! WEXEmoticonModel
//        type等于1 表示是emoji表情
        if emoticon.type == "1" {
            
            tv_textView.insertText((emoticon.code! as NSString).emoji())
//        表示是图片表情
        }else{
            
            tv_textView.insertEmoticon(emoticon)
            
        }
        
        
    }
    
    // 删除按钮点击
    @objc private func deleteButtonClick(){
        
      tv_textView.deleteBackward()
        
    }
    // 键盘位移点击
    @objc private func keyboardChangeFrame(notif: NSNotification) {
        
//        通过键盘的最后停止位置获得键盘的frame
        let endFrame = (notif.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        stk_toolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(endFrame.origin.y - SCREENHEIGHT)
        }
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
        
    }
    // 返回按钮点击
    @objc private func back(){
        tv_textView.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 发送按钮的点击
    @objc private func send() {
        
        if cv_pictureView.hidden {
            
            updata()
        }else{
            
            upload()
        }
        
    }
    
    // MARK: - 实现发送方法
    
    // 发送文字微博
    private func updata(){
        
        // 请求地址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        // 请求参数
        let params = [
            "access_token": WEXUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "status": tv_textView.emoticonText!
        ]
        
        WEXNetworkTools.sharedTools.request(WEXRequestMethod.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            
            if error != nil{
                
                print("发送失败\(error)")
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                
                return
            }else{
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }
        }
        
    }
    
    
    // 发送图片微博
    private func upload(){
        
        // 请求地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        // 请求参数
        let params = [
            "access_token": WEXUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "status": tv_textView.emoticonText!
        ]

        let data = UIImagePNGRepresentation(self.cv_pictureView.images.first!)!
        
        WEXNetworkTools.sharedTools.upload(urlString, parameters: params, datas: ["pic": data]) { (responseObject, error) -> () in
            
            if error != nil{
                
                print("发送失败\(error)")
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                
            }else{
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
            }
        }
        
    }
    
    
    // MARK: - 懒加载子控件
    
    // 键盘
    private lazy var uv_keyBoard: WEXEmoticonKeyBoard = {
        
        let keyBoard = WEXEmoticonKeyBoard()
        
        keyBoard.frame.size = CGSize(width: SCREENWIDTH, height: 216)
       
        
        return keyBoard
    }()
    
    // 图片界面
    private lazy var cv_pictureView: WEXComposePictureView = {
        
        let picView = WEXComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        
        picView.selectPictureClosure = { [weak self] in
            
            self?.selectPicture()
            
        }
        
        return picView
    
    }()
    
    
    // 界面右上角的按钮
    private lazy var btn_rightButton: UIButton = {
       

        let rightButton = UIButton(textColor: UIColor.whiteColor(), textFont: 18)
        rightButton.setTitle("发送", forState: UIControlState.Normal)
        rightButton.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside)
        // 设置不同状态下的背景图
        rightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置不同状态的文字颜色
        rightButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        
        rightButton.frame.size = CGSize(width: 45, height: 28)
        
        return rightButton
    }()
    
    // nav的titleView
    private lazy var lb_title: UILabel = {
        
        let title = UILabel()
        
        title.numberOfLines = 0
        
        title.textColor = UIColor.blackColor()
        
        title.font = UIFont.systemFontOfSize(14)
        
        title.textAlignment = .Center
        
        if let name = WEXUserAccountViewModel.sharedViewModel.account?.name{
            
            let text = "发微博\n\(name)"
            let range = (text as NSString).rangeOfString(name)
            
            let attribute = NSMutableAttributedString(string: text)
            
            attribute.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(18)], range: range)
            
            title.attributedText = attribute
        }else{
            
            title.text = "发微博"
        }
        
        title.sizeToFit()
        return title
        
    }()
    
    // textView
    private lazy var tv_textView: WEXTextView = {
    
        let textView = WEXTextView()
        
        textView.delegate = self
        
        textView.placeholder = "我就是出来测试测试"
        
        textView.font = UIFont.systemFontOfSize(16)
        
//        添加拖拽的时候dismiss键盘的功能
        textView.keyboardDismissMode = .OnDrag
//        开启垂直方向的弹簧效果
        textView.alwaysBounceVertical = true
        
        return textView
    
    }()
    
    // 下排状态栏
    private lazy var stk_toolBar: WEXComposeToolBar = {
    
   let toolBar = WEXComposeToolBar(frame: CGRectZero)
        
        toolBar.childButtonClosure = {[weak self] (type: WEXComposeToolBarButtonType) in
            
            switch type {
            case .Picture:
                self?.selectPicture()
                break
            case .Mention:
                break
            case .Trend:
                break
            case .Emoticon:
                self?.selectKeyBoard()
                break
            case .Add:
                break
            }

        }
        
        return toolBar
    
    }()
    
    
}

// MARK: - 实现代理方法
extension WEXComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
//        根据textView是否有数据，判断右边按钮是否可点击
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
}

extension WEXComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let img = image.scaleToWidth(600)
        
        cv_pictureView.addImage(img)
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}
